import axios from 'axios';
import { post } from './axios';
import { ApiResponse, UploadResult } from '../types/api';

/**
 * 文件上传API服务
 */
export const UploadApi = {
  /**
   * 上传图片
   * @param file 文件对象
   * @param onProgress 进度回调函数
   * @returns 上传结果
   */
  uploadImage: (file: File, onProgress?: (percentage: number) => void): Promise<ApiResponse<UploadResult>> => {
    const formData = new FormData();
    formData.append('file', file);

    return new Promise((resolve, reject) => {
      const instance = axios.create({
        baseURL: import.meta.env.VITE_API_URL || '/api',
        timeout: 60000, // 上传文件可能需要更长的超时时间
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });

      // 添加授权头
      const token = localStorage.getItem('token');
      if (token) {
        instance.defaults.headers.common['Authorization'] = `Bearer ${token}`;
      }

      // 上传请求
      instance.post('/upload/image', formData, {
        onUploadProgress: (progressEvent) => {
          if (progressEvent.total && onProgress) {
            const percentage = Math.round((progressEvent.loaded * 100) / progressEvent.total);
            onProgress(percentage);
          }
        }
      }).then(response => {
        resolve(response.data);
      }).catch(error => {
        reject(error);
      });
    });
  },

  /**
   * 删除已上传图片
   * @param fileName 文件名
   * @returns 删除结果
   */
  deleteImage: (fileName: string): Promise<ApiResponse> => {
    return post('/upload/delete-image', { fileName });
  }
}; 